package com.sx.pipeline.ui.register

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.app.config.RegisterType
import com.sx.pipeline.app.config.SmsCodeType
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.ActPersonalRegisterBinding
import com.sx.pipeline.repos.http.res.AttributeList
import com.sx.pipeline.repos.http.res.ProvincesVO
import com.sx.pipeline.repos.http.res.UnitNameVO
import com.sx.pipeline.repos.http.res.UnitTypeVO
import com.sx.pipeline.ui.register.adapter.SelectUnitNameAdapter
import com.sx.pipeline.ui.register.adapter.SelectUnitTypeAdapter
import com.sx.pipeline.utils.ItemDecorationUtils
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers


/**
 * @Author: YY
 * @Date: 2022/4/14
 * @Description: 个人注册
 */
@Route(path = RoutePath.Register.REG_PERSONAL)
class PersonalRegisterActivity : CYDataBindingBaseActivity<ActPersonalRegisterBinding, RegisterVM>
    (R.layout.act_personal_register), View.OnClickListener {

    @Autowired(name = IntentKey.ID)
    @JvmField
    var identityID: Int? = 0

    // 单位类型
    private lateinit var selectUnitTypeAdapter: SelectUnitTypeAdapter

    // 单位名称
    private lateinit var selectUnitNameAdapter: SelectUnitNameAdapter

    override fun initStatusBar() {
        ImmersionBar.with(this).statusBarDarkFont(true)
            .fitsSystemWindows(false).init()
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)

        // 注册类型和身份
        mViewModel.registerTypeField.set(RegisterType.PERSONAL_REG.code)
        mViewModel.identityField.set(identityID)

        // 身份类型
        when (identityID) {
            IdentityType.OPERATING_UNIT.code -> {
                // 运营单位
                mBinding.tvRegisterTips.text =
                    "${IdentityType.OPERATING_UNIT.flag}-${getString(R.string.txt_personal_reg)}"
                // 获取单位类型和名称
                mViewModel.getUnitType(identityID)
                // 显示相关控件
                isShowWidget(true)
            }
            IdentityType.BUILD_UNIT.code -> {
                // 施工单位
                mBinding.tvRegisterTips.text =
                    "${IdentityType.BUILD_UNIT.flag}-${getString(R.string.txt_personal_reg)}"
                // 隐藏相关控件
                isShowWidget(false)
            }
            IdentityType.SUPPLIER.code -> {
                // 供应商
                mBinding.tvRegisterTips.text =
                    "${IdentityType.SUPPLIER.flag}-${getString(R.string.txt_personal_reg)}"
                // 隐藏相关控件
                isShowWidget(false)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        mBinding.tvCountDown.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.tvCountDown.stop()
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.image_left_gray -> {
                // 返回
                finish()
            }
            R.id.tv_count_down -> {
                // 获取验证码
                val phone = mBinding.etPhone.text.toString()
                // 获取验证码
                mViewModel.sendSmsCode(phone, SmsCodeType.REGISTER_SMS.code)
            }
            R.id.sb_address -> {
                // 选择地址
                showProvincesDialog()
            }
            R.id.sb_unit_name -> {
                // 选择单位
                mViewModel.getUnitNameList()
            }
            R.id.tv_privacy_agree -> {
                // 隐私协议
                mViewModel.getAgreement(1)
            }
            R.id.tv_user_agree -> {
                // 用户协议
                mViewModel.getAgreement(2)
            }
            R.id.tv_refresh -> {
                // 重新获取单位类型和名称
                mViewModel.getUnitType(identityID)
            }
            R.id.tv_register -> {
                // 注册
                register()
            }
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()

        // 验证码状态
        observe(mViewModel.smsCodeEvent) {
            mBinding.tvCountDown.start()
        }

        // 协议
        observe(mViewModel.agreementEvent) {
            RouteManager.Register.intentToAgreement(it!!)
        }

        if (identityID == IdentityType.OPERATING_UNIT.code) {
            // 单位类型
            setUnitTypeList()
        }

        // 单位名称列表
        showUnitNameDialog()

        //注册成功
        observe(mViewModel.registerSuccessEvent) {
            XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .isDestroyOnDismiss(true)
                .asConfirm(getString(R.string.hint), getString(R.string.txt_register_success_tips),
                    getString(R.string.cancel), getString(R.string.confirm),
                    {
                        ActivityUtils.finishActivity(SelectTypeIDRegActivity::class.java)
                        finish()
                    }, { }, true
                ).show()

        }
    }

    /**
     * 单位类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setUnitTypeList() {

        mBinding.recyclerUnitType.addItemDecoration(
            ItemDecorationUtils(4, 6, 4, 6, 0)
        )
        mBinding.recyclerUnitType.layoutManager = FlexboxLayoutManager(
            this,
            FlexDirection.ROW, FlexWrap.WRAP
        )

        // 单位类型
        observe(mViewModel.unitTypeListEvent) {
            if (it.isNullOrEmpty()) {
            } else {
                // 单位类型id
                mViewModel.unitTypeIdsField.set(it[0].id.toString())
                // 单位类型名称
                mViewModel.unitTypeNameField.set(it[0].name)

                if (!this::selectUnitTypeAdapter.isInitialized) {
                    selectUnitTypeAdapter =
                        SelectUnitTypeAdapter(it as MutableList<UnitTypeVO>, false)
                }
                mBinding.recyclerUnitType.adapter = selectUnitTypeAdapter
                // item点击事件
                selectUnitTypeAdapter.setOnItemClickListener { adapter, _, position ->
                    // 单选
                    selectUnitTypeAdapter.setSelectClickId(position)
                    val unitTypeVO = adapter.data[position] as UnitTypeVO
                    // 单位类型id
                    mViewModel.unitTypeIdsField.set(unitTypeVO.id.toString())
                    // 单位名称
                    mViewModel.unitTypeNameField.set(unitTypeVO.name)
                    // 选择单位名称
                    selectUnitName(it, position)
                }
                // 选择单位名称 默认0
                selectUnitName(it)
            }
        }
    }

    private fun selectUnitName(it: List<UnitTypeVO>, position: Int = 0) {
        mBinding.sbUnitName.rightText = ""
        mBinding.tvSelectUnit.text = "单位名称"
        setUnitNameList(it, position)
    }

    /**
     * 单位名称列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setUnitNameList(it: List<UnitTypeVO>?, selectPosition: Int = 0) {
        if (!it!![selectPosition].attributeList.isNullOrEmpty()) {
            mBinding.recyclerUnitName.visibility = View.VISIBLE

            // 属性名称
            mViewModel.typeAttributeField.set(it[selectPosition].attributeList?.get(0)!!.attributeName)
            if (!this::selectUnitNameAdapter.isInitialized) {
                mBinding.recyclerUnitName.addItemDecoration(
                    ItemDecorationUtils(4, 6, 4, 6, 0)
                )
                mBinding.recyclerUnitName.layoutManager = FlexboxLayoutManager(
                    this,
                    FlexDirection.ROW, FlexWrap.WRAP
                )

                selectUnitNameAdapter =
                    SelectUnitNameAdapter(it[selectPosition].attributeList as MutableList<AttributeList>)
                mBinding.recyclerUnitName.adapter = selectUnitNameAdapter
            }
            selectUnitNameAdapter.data =
                it[selectPosition].attributeList as MutableList<AttributeList>
            selectUnitNameAdapter.notifyDataSetChanged()
            // Item点击事件
            selectUnitNameAdapter.setOnItemClickListener { adapter, view, position ->
                selectUnitNameAdapter.setSelectClickId(position)
                // 属性名称
                mViewModel.typeAttributeField.set(it[selectPosition].attributeList?.get(position)!!.attributeName)
            }
        } else {
            mBinding.recyclerUnitName.visibility = View.GONE
            mViewModel.typeAttributeField.set(null)
        }
    }


    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity(), true)
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String, v: View?,
            ) {
                Logs.d("showProvincesDialog ${province+provincesVO?.id?.toInt()+city+cityVO?.id?.toInt()+areaVO+areaVO?.id?.toInt()}")
                // 显示地址
                mBinding.sbAddress.setLeftTextColor(Color.parseColor("#666666"))
                mBinding.sbAddress.leftText = "$province $city $area"

                Logs.d("showProvincesDialog ${areaVO!!.id.toInt()}")
                // 省市区id及详细地址
                mViewModel.provinceIDField.set(provincesVO!!.id.toInt())
                mViewModel.cityIDField.set(cityVO!!.id.toInt())
                mViewModel.areaIDField.set(areaVO!!.id.toInt())
                mViewModel.addressField.set("$province $city $area")

                mBinding.sbUnitName.leftText = "请选择单位名称"
                mViewModel.unitNameField.set("")
                if("全部".equals(area)){
                    mViewModel.locationId.set(cityVO!!.id.toInt())
                }else{
                    mViewModel.locationId.set(areaVO!!.id.toInt())
                }
            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(this).asCustom(popup).show()
    }

    /**
     * 选择单位
     */
    private fun showUnitNameDialog() {
        observe(mViewModel.unitNameListEvent) { data ->
            Observable.fromIterable(data)
                .map { unitNameVO -> unitNameVO.name }.toList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    XPopup.Builder(this)
                        .asBottomList(
                            "选择单位", it.toTypedArray()
                        ) { position, text ->
                            val unitNameVO: UnitNameVO = data!![position]
                            // 选择单位id
                            mBinding.sbUnitName.setLeftTextColor(Color.parseColor("#666666"))
                            mBinding.sbUnitName.leftText = unitNameVO.name
                            mViewModel.selectUnitIdField.set(unitNameVO.id)
                            mViewModel.unitNameField.set(unitNameVO.name)
                            // 单位信息所携带得所属地址信息
                            mViewModel.provinceIDField.set(unitNameVO.provinceId.toInt())
                            mViewModel.cityIDField.set(unitNameVO.cityId.toInt())
                            mViewModel.areaIDField.set(unitNameVO.areaId.toInt())
                            mViewModel.addressField.set(unitNameVO.addressDetail)
                            mBinding.sbAddress.setLeftTextColor(Color.parseColor("#666666"))
                            mBinding.sbAddress.leftText = unitNameVO.addressDetail
                        }.show()
                })
        }
    }

    /**
     * 注册
     */
    private fun register() {
        val name = mBinding.etName.text.toString()
        val phone = mBinding.etPhone.text.toString()
        val smsCode = mBinding.etVerifyCode.text.toString()
        val superiorName = mBinding.etSuperiorName.text.toString()
        val superiorPhone = mBinding.etSuperiorPhone.text.toString()
        val isCheck = mBinding.toggleAgree.isChecked
        // 注册
        mViewModel.personalRegister(name, phone, smsCode, superiorName, superiorPhone, isCheck)
    }

    /**
     * 是否显示相关组件
     */
    private fun isShowWidget(isShow: Boolean) {
        if (isShow) {
            // 显示相关控件
            mBinding.tvUnitType.visibility = View.VISIBLE
            mBinding.recyclerUnitType.visibility = View.VISIBLE
            mBinding.recyclerUnitName.visibility = View.VISIBLE
            return
        }
        // 隐藏相关控件
        mBinding.tvUnitType.visibility = View.GONE
        mBinding.recyclerUnitType.visibility = View.GONE
        mBinding.recyclerUnitName.visibility = View.GONE
    }
}